package com.example.shiro.core.session;

import com.example.shiro.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @author lijilong
 * @version 1.0
 * @Description:
 * @CreateDate 2018/8/10 17:18
 */
@Slf4j
public class RedisSessionDao extends AbstractSessionDAO {
    @Autowired
    RedisService redisService;
    private static final String SHIRO_SESSION_PREFIX = "shiro_session:";

    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        log.info(sessionId.toString());
        // 把sessionId 和 session绑定
        assignSessionId(session, sessionId);
        redisService.setObj(SHIRO_SESSION_PREFIX + sessionId, session);
        redisService.expire(SHIRO_SESSION_PREFIX + sessionId, 300);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        log.info("read session");
        if(sessionId == null){
            return null;
        }
        Session session = (Session) redisService.getObj(SHIRO_SESSION_PREFIX + sessionId);
        return session;
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        Serializable sessionId = session.getId();
        redisService.setObj(SHIRO_SESSION_PREFIX + sessionId, session);
        redisService.expire(SHIRO_SESSION_PREFIX + sessionId, 30);
    }

    @Override
    public void delete(Session session) {
        Serializable sessionId = session.getId();
        redisService.delete(SHIRO_SESSION_PREFIX + sessionId);
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<String> keys = redisService.keys(SHIRO_SESSION_PREFIX);
        Set<Session> sessions = new HashSet<>();
        if(CollectionUtils.isEmpty(keys)){
            return sessions;
        }
        for(String key : keys){
            Session session = (Session) redisService.getObj(key);
            sessions.add(session);
        }
        return sessions;
    }
}
